import React from 'react';
import { message } from 'antd';
class Geolocation extends React.Component {
  constructor(props) {
    super(props);
    if (typeof window !== 'undefined') {
      if (!props.__map__) {
        throw new Error('Geolocation has to be a child of Map component');
      } else {
        this.map = props.__map__;
        this.element = props.__ele__;

        this.resolveGeolocation(props).then(() => {
          this.triggerCreated(props);
          this.map.addControl(this.geolocation);
          //
          // this.geolocation.getCityInfo((status, result) => {
          //   //console.log('geo info', status, result);
          //   this.props.onOk && this.props.onOk(result);
          // });
          this.geolocation.getCurrentPosition();
        });
      }
    }
  }

  shouldComponentUpdate() {
    return false;
  }
  componentWillUnmount() {
    window.AMap.event.removeListener(this.errorListener);
    window.AMap.event.removeListener(this.completeListener);
  }
  onError = ErrorStatus => {
    //console.log('geo error', ErrorStatus);
    this.props.onError && this.props.onError();
  };
  onComplete = GeolocationResult => {
    //console.log('geo complete', GeolocationResult);
    this.props.onOk(GeolocationResult);
  };

  resolveGeolocation(props) {
    if (this.geolocation) {
      return new Promise(resolve => {
        resolve(this.geolocation);
      });
    } else {
      return new Promise(resolve => {
        this.map.plugin(['AMap.Geolocation'], () => {
          this.geolocation = new window.AMap.Geolocation(props);
          //console.log('Amap', window.AMap);
          this.errorListener = window.AMap.event.addListener(
            this.geolocation,
            'error',
            this.onError
          );
          this.completeListener = window.AMap.event.addListener(
            this.geolocation,
            'complete',
            this.onComplete
          );
          resolve(this.geolocation);
        });
      });
    }
  }

  triggerCreated(props) {
    const events = props.events || {};
    if ('created' in events && typeof events.created === 'function') {
      events.created(this.geolocation);
    }
  }

  render() {
    return null;
  }
}

export default Geolocation;
